package com.system.comm.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.system.comm.utils.FrameJsonUtil;
import com.system.comm.utils.FrameTimeUtil;

public class BaseRestController {

	public static final Logger LOGGER = LoggerFactory.getLogger(BaseRestController.class);
	
	public static final String UTF_8 = "utf-8";

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat(FrameTimeUtil.FMT_YYYY_MM_DD);
			dateFormat.setLenient(false);
			// true:允许输入空值，false:不能为空值
			binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		} catch (Exception e) {
			SimpleDateFormat dateFormat = new SimpleDateFormat(FrameTimeUtil.FMT_DEFAULT);
			dateFormat.setLenient(false);
			// true:允许输入空值，false:不能为空值
			binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		}
	}

	public void writerJson(HttpServletResponse response, Object obj) {
		/*
		 * try { response.setContentType("text/html;charset=UTF-8"); ObjectMapper mapper
		 * = new ObjectMapper(); StringWriter sw = new StringWriter(); JsonGenerator gen
		 * = new JsonFactory().createJsonGenerator(sw); mapper.writeValue(gen, obj);
		 * response.getWriter().print(sw.toString()); } catch (IOException e) {
		 * logger.error(e.getMessage()); }
		 */
		try {
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print(FrameJsonUtil.toString(obj));
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
	}
}
